package com.amigo.online.amigo.online.provider.mimc.utils

import com.alibaba.fastjson.JSONObject
import com.amigo.online.amigo.online.provider.mimc.config.body
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

object HttpUtil {

    private const val TIMEOUT = 30L
    private val TIMEUNIT = TimeUnit.SECONDS

    private val interceptor: HttpLoggingInterceptor  by lazy {
        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
    }
    private val httpClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TIMEUNIT)
                .readTimeout(TIMEOUT, TIMEUNIT)
                .addInterceptor(interceptor)
                .build()
    }

    fun post(url: String, body: JSONObject): String {
        val response = httpClient.newCall(getRequest(url, body.body())).execute()
        return response.body()?.string() ?: ""
    }

    private fun getRequest(url: String, body: RequestBody): Request {
        return Request.Builder().url(url).post(body).build()
    }
}

